package com.yanqu.road.logic.xlogic.rank.base;

import com.yanqu.road.logic.helper.RankHelper;

import java.util.HashSet;
import java.util.Set;

public abstract class AbstractXRankListModel {

    /**
     * 入库信息
     */
    protected String dbName;
    protected String tableName;

    /**
     * 需要入库的rank
     */
    private final Set<Integer> needDbSet = new HashSet<>();

    public AbstractXRankListModel(String dbName, String tableName) {
        this.dbName = dbName;
        this.tableName = tableName;
    }

    public abstract void save();

    /**
     * 添加需要入库的rank
     *
     * @param oldRank 旧排行，-1或超出rankNum表示不在榜单内
     * @param newRank 新排行，-1或超出rankNum表示不在榜单内
     * @param maxRank 榜单长度
     */
    protected void addDbRank(int oldRank, int newRank, int maxRank) {
        synchronized (needDbSet) {
            needDbSet.addAll(RankHelper.calNeedDbRank(oldRank, newRank, maxRank));
        }
    }

    /**
     * 全部rank添加入库
     */
    protected void addAllDbRank(int maxRank) {
        synchronized (needDbSet) {
            for (int i = 1; i <= maxRank; i++) {
                needDbSet.add(i);
            }
        }
    }

    /**
     * 获取并清空需要入库的rank
     */
    protected Set<Integer> getAndClearAllDbRank() {
        Set<Integer> list;
        synchronized (needDbSet) {
            list = new HashSet<>(needDbSet);
            needDbSet.clear();
        }
        return list;
    }
}
